#!/bin/bash

PATH_LIB=$OSVC_PATH_COMP/com.replication-manager
PREFIX=OSVC_COMP_DB

typeset -i r=0
typeset -i OSVC_COMP_CHECKPOINTIOPS OSVC_COMP_IBPINSTANCES
export OSVC_COMP_CHECKPOINTIOPS=$(($OSVC_COMP_SVC_CONF_ENV_MAX_IOPS/2))
IBPINSTANCES_CORES=$(($OSVC_COMP_NODES_CPU_CORES/4))
IBPINSTANCES_MAX_MEM=$(($OSVC_COMP_SVC_CONF_ENV_MAX_MEM/1024/8))
export OSVC_COMP_IBPINSTANCES=$(($IBPINSTANCES_CORES > $IBPINSTANCES_MAX_MEM ? $IBPINSTANCES_CORES : $IBPINSTANCES_MAX_MEM))
[ $OSVC_COMP_IBPINSTANCES -lt 1 ] && OSVC_COMP_IBPINSTANCES=1
[ $OSVC_COMP_IBPINSTANCES -gt 64 ] && OSVC_COMP_IBPINSTANCES=64

case $1 in
check)
	for pod in $(echo /$OSVC_COMP_SVC_CONF_ENV_BASE_DIR/pod*)
	do
		export OSVC_COMP_POD=$(basename $pod)
		typeset padded_n="$(echo $OSVC_COMP_POD | sed -e "s@pod@@")"
		typeset -i n=$(echo $OSVC_COMP_POD | sed -e "s@pod[0]*@@")
		export OSVC_COMP_SERVER_ID=$n
		server_port="OSVC_COMP_SVC_CONF_ENV_PORT_POD$padded_n"
		export OSVC_COMP_SERVER_PORT=${!server_port}
		server_ip="OSVC_COMP_SVC_CONF_ENV_IP_POD$padded_n"
		export OSVC_COMP_SERVER_IP=${!server_ip}
#		IFS=. read -r a b c d <<< "${!server_ip}"
#		export OSVC_COMP_SERVER_ID="$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"

		$OSVC_PYTHON $PATH_LIB/file.py ${PREFIX}_CNF check
		[ $? -eq 1 ] && r=1
		$OSVC_PYTHON $PATH_LIB/symlink.py ${PREFIX}_LINK check
		[ $? -eq 1 ] && r=1
	done
	exit $r
	;;
fix)
	for pod in $(echo /$OSVC_COMP_SVC_CONF_ENV_BASE_DIR/pod*)
	do
		export OSVC_COMP_POD=$(basename $pod)
		typeset padded_n="$(echo $OSVC_COMP_POD | sed -e "s@pod@@")"
		typeset -i n=$(echo $OSVC_COMP_POD | sed -e "s@pod[0]*@@")
		export OSVC_COMP_SERVER_ID=$n
		server_port="OSVC_COMP_SVC_CONF_ENV_PORT_POD$padded_n"
		export OSVC_COMP_SERVER_PORT=${!server_port}
		server_ip="OSVC_COMP_SVC_CONF_ENV_IP_POD$padded_n"
		export OSVC_COMP_SERVER_IP=${!server_ip}
	#	IFS=. read -r a b c d <<< "${!server_ip}"
	#	export OSVC_COMP_SERVER_ID="$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
		$OSVC_PYTHON $PATH_LIB/file.py ${PREFIX}_CNF fix
		[ $? -eq 1 ] && exit 1
		$OSVC_PYTHON $PATH_LIB/symlink.py ${PREFIX}_LINK fix
		[ $? -eq 1 ] && exit 1
	done
	exit 0
	;;
fixable)
	exit 2
	;;
esac
